<template>
    <div>
        <!-- 搜索卡片  查询条件：课程名称、课程类型、开始时间、结束时间 -->
        <el-card>
            <el-form :model="queryForm" :inline="true">
                <el-form-item label="课程名称">
                    <el-input type="text" placeholder="请输入课程名称" v-model="queryForm.name" size="small"></el-input>
                </el-form-item>
                <el-form-item label="课程类型">
                    <el-input type="text" placeholder="输入课程类型" v-model="queryForm.type" size="small"></el-input>
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-date-picker value-format="yyyy-MM-dd" size="small" type="date" placeholder="请选择开始日期" v-model="queryForm.startTime"></el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker value-format="yyyy-MM-dd" size="small" type="date" placeholder="请选择结束日期" v-model="queryForm.endTime"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="small" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 数据卡片 -->
        <el-card class="mt12" style="margin-top: 10px">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-s-operation" type="success" plain @click="handleAssigned()" v-if="hasPerm()">安排</el-button>
                    <el-button size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd()" v-if="!hasPerm()">新增</el-button>
                    <el-button size="small" icon="el-icon-delete" type="danger" plain @click="handleBatchDelete()" v-if="!hasPerm()">删除</el-button>
                </div>
            </div>
            <!-- 数据表格 -->
            <el-table
                :data="courseList"
                v-loading="loading"
                border
                fit
                :header-cell-style="{background:'#f8f8f9',color:'#5a516e',padding:'10px 0px'}"
                :cell-style="{padding:'5px 0px'}"
                @selection-change="handleSelectionChange"
                style="margin: 10px 0">
                <el-table-column type="selection" align="center" width="50px"></el-table-column>
                <el-table-column label="课程名称" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.name }}
                    </template>
                </el-table-column>
                <el-table-column label="课程描述" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.description }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="任课教师" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.teacher }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="课程类型" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.type }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="学分" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.credit }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="开始时间" align="center">
                    <template slot-scope="scope">
                        <span>{{ formatDate(scope.row.startTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="结束时间" align="center">
                    <template slot-scope="scope">
                        <span>{{ formatDate(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="考勤规则" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.rules }}</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="操 作" align="center" width="200" v-if="!hasPerm()">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id,scope.row.teacher)">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                :current-page="queryForm.pageNum"
                :page-size="queryForm.pageSize"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange">
            </el-pagination>
        </el-card>
        <!-- 新增和编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="show" width="60%">
            <el-form :model="submitForm" :inline="true" label-width="120px" :rules="rules" ref="submitForm">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="课程名称" prop="name">
                            <el-input type="text" placeholder="请输入课程名称" v-model="submitForm.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="课程描述" prop="description">
                            <el-input type="text" placeholder="请输入课程描述" v-model="submitForm.description"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学分" prop="credit">
                            <el-input type="text" placeholder="请输入学分" v-model="submitForm.credit" @input="handleInput"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="课程类型" prop="type">
                            <el-input type="text" placeholder="请输入课程类型" v-model="submitForm.type"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="选择教师" prop="teacherId">
                            <el-select v-model="selectedTeacher" placeholder="请选择教师">
                                <el-option
                                    v-for="teacher in teachers"
                                    :key="teacher.id"
                                    :label="teacher.username"
                                    :value="teacher.id"
                                    @click.native="handleTeacherClick(teacher.username)"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="课程时间" prop="daterange">
                            <el-date-picker
                                v-model="daterange"
                                type="daterange"
                                range-separator="到"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                size="default"
                                :picker-options="pickerOptions"
                                @change="handleDateRangeChange"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="考勤规则" prop="rulesText">
                            <el-input type="textarea" :rows="5" :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入自然语言考勤规则" v-model="rulesText"></el-input>
                        </el-form-item>
                        <el-button type="primary" @click="handleRulesText" style="margin:10px;">生成规则日历</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item style="line-height: normal;">
                            <el-calendar v-loading="loadingClandar">
                                <div slot="dateCell" slot-scope="{ data }" @click="handleClick(data.day)">
                                    <div class="date-content" style="line-height: normal;" >
                                        <span class="date-number" style="line-height: normal;font-weight: bold;">{{ data.day.split('-').slice(-1)[0] }}</span>
                                        <div v-if="events[data.day]" class="event-item" style="color: darkblue;" >
                                            {{ submitForm.name  }}<br>
                                            {{ selectedTeacherName }}<br>
                                            {{ events[data.day] }}
                                        </div>
                                        <div v-else class="event-item" style="color: darkblue;height:100%;"><br><br><br></div>
                                        
                                    </div>
                                </div>
                                
                            </el-calendar>
                        </el-form-item>
                    </el-col> 
                </el-row>
                <el-row v-if="showRangeTime">
                    <el-col :span="24">
                        <el-form-item label="考勤时间范围">
                            <el-time-picker  is-range
                                arrow-control
                                v-model="rangeTime"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                placeholder="选择时间范围">
                            </el-time-picker>
                        </el-form-item>
                        <el-button type="primary" @click="handleClickRangeTime" style="margin:10px;">设置</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <div class="dialog-footer" slot="footer" style="margin-right: 40px;">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCourses, getCourse, addCourse, updateCourse, deleteCourse } from '@/api/course'
import { listTeachers } from '@/api/teacher'
import { getCron } from '@/api/openai' 
import { addAssignedList } from '@/api/assigned'
import { parseTime,findSpecificWeekdays } from '@/utils/date'

export default {
    name: 'Course',
    data() {
        const validateDateRange = (rule, daterange, callback)=>{
            if (!this.daterange || this.daterange.length !== 2) {
                callback(new Error('请选择课程时间'));
            } else {
                callback();
            }
        }
        return {
            loading: true,
            submitForm: {},
            title: "新增",
            show: false,
            total: 120,
            daterange:[],
            queryForm: {
                pageNum: 1,
                pageSize: 10
            },
            courseList: [],
            selectList: [],
            selectedTeacher: '',
            selectedTeacherName: '',
            rulesText: '',
            loadingClandar: false,
            events: {},
            teachers: [],
            tempDate:{},
            showRangeTime: false,
            rangeTime:[new Date(0,0,0,8,0,0), new Date(0,0,0,9,0,0)],
            rules: {
                name: [
                    { required: true, message: '请输入课程名称', trigger: 'blur' }
                ],
                teacherId: [
                    { required: true, message: '请输入任课教师工号', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请输入课程类型', trigger: 'blur' }
                ],
                credit: [
                    { required: true, message: '请输入学分', trigger: 'blur' }
                ],
                daterange: [
                    { validator: validateDateRange, trigger: 'blur' }
                ]
            },
            headers: {
                Authorization: 'Bearer ' + this.$Cookie.get('login-token')
            },
            pickerOptions: {
                disabledDate(time) {
                // 不允许选择过去的时间
                    return time.getTime() < Date.now() - 8.64e7;
                }
            }
        }
    },
    created() {
        this.getList()
        this.loadTeachers()
    },
    methods: {
        handleSubmit() {
            this.submitForm.teacherId = this.selectedTeacher
            this.$refs['submitForm'].validate((valid) => {
                if (valid) {
                    this.submitForm.credit = parseFloat(this.submitForm.credit)
                    this.submitForm.rules = JSON.stringify(this.events)
                    if (this.title === "编辑") {
                        this.submitForm.updateBy = this.$Cookie.get("username")
                        updateCourse(this.submitForm).then(res => {
                            this.show = false
                            this.getList()
                            this.submitForm = {}
                        }).catch(err => {
                            console.log(err)
                        })
                    } else {
                        this.submitForm.createBy = this.$Cookie.get("username")
                        addCourse(this.submitForm).then(res => {
                            this.show = false
                            this.getList()
                            this.submitForm = {}
                        }).catch(err => {
                            console.log(err)
                        })
                    }
                }
            })
        },
        handleReset() {
            this.queryForm = {
                pageNum: 1,
                pageSize: 10
            }
            this.getList()
        },
        handleSearch() {
            this.queryForm.pageNum = 1
            this.getList()
        },
        handleSizeChange(pageSize) {
            this.queryForm.pageSize = pageSize
            this.queryForm.pageNum = 1
            this.getList()
        },
        handleCurrentChange(pageNum) {
            this.queryForm.pageNum = pageNum
            this.getList()
        },
        getList() {
            this.loading = true
            listCourses(this.queryForm).then(res => {
                this.courseList = res.data.records
                this.total = res.data.total
                this.loading = false
            }).catch(err => {})
        },
        handleDelete(ids) {
            this.$confirm("你确定删除id为" + ids + "的记录吗？", "提示", {
                cancelButtonText: "取消",
                confirmButtonText: "确定",
                type: "warning"
            }).then(() => {
                deleteCourse(ids).then(res => {
                    this.$message("删除成功")
                    this.getList()
                }).catch(err => {
                    console.log(err)
                })
            }).catch(() => {})
        },
        handleAdd() {
            this.show = true
            this.title = "新增"
            this.submitForm = {}
            this.events = {}
            this.showRangeTime = false
            this.rulesText = ''
            this.daterange = {}
        },
        handleCancel() {
            this.show = false
            this.showRangeTime = false
        },
        handleEdit(id,teacherName) {
            getCourse(id).then(res => {
                this.title = "编辑"
                this.show = true
                this.loadingClandar = false
                this.showRangeTime = false
                this.submitForm = res.data
                this.selectedTeacher = res.data.teacherId
                this.selectedTeacherName = teacherName
                this.daterange = [res.data.startTime, res.data.endTime]
                this.events = JSON.parse(res.data.rules)
                this.rulesText = ''
            }).catch(err => {
                console.log(err)
            })
        },
        handleBatchDelete() {
            if (this.selectList) {
                let ids = this.selectList.map(o => { return o.id })
                this.handleDelete(ids)
            }
        },
        handleSelectionChange(val) {
            this.selectList = val
        },
        formatDate(value, format) {
            return parseTime(new Date(value), format)
        },
        async loadTeachers() {
            listTeachers({pageNum:1,pageSize:100}).then(res => {
                this.teachers = res.data.records
            })
        },
        handleInput(value) {
            this.submitForm.credit = value.replace(/[^0-9.]/g, '');
            if (this.submitForm.credit.split('.').length > 2) {
                this.submitForm.credit = this.submitForm.credit.slice(0, -1);   
            }
        },
        handleDateRangeChange(daterange) {
            if (daterange && daterange.length === 2) {
                this.submitForm.startTime = this.formatDate(daterange["0"], '{y}-{m}-{d}');
                this.submitForm.endTime = this.formatDate(daterange["1"], '{y}-{m}-{d}');
            } else {
                this.submitForm.startTime = null;
                this.submitForm.endTime = null;
            }
        },
        handleRulesText(){
            this.loadingClandar = true
            getCron(this.rulesText).then(resp => {
                this.events = {};
                for(let x in resp.dates){
                    let date = resp.dates[x];
                    this.events = {...this.events,
                                   ...findSpecificWeekdays(this.formatDate(this.daterange["0"], '{y}-{m}-{d}'),
                                         this.formatDate(this.daterange["1"], '{y}-{m}-{d}'),
                                         date.week,date.range_time)
                                  }
                }
                this.loadingClandar = false;
                this.submitForm.rules = this.events;
            }).catch(error => {
                console.error("获取失败:", error);
            });
        },
        handleTeacherClick(teacherName){
            this.selectedTeacherName = teacherName
        },
        handleClick(date){
            if(this.events[date]){
                this.$delete(this.events, date);
            }else{
                this.showRangeTime = true
                this.tempDate = date
            }
        },
        handleClickRangeTime(){
            this.$set(this.events,this.tempDate,this.formatDate(this.rangeTime[0],"{h}:{i}")+" - "+this.formatDate(this.rangeTime[1],"{h}:{i}"));
            this.showRangeTime = false
        },
        hasPerm(){
            return sessionStorage.getItem('studentIds') !== null
        },
        handleAssigned(){
            if (this.hasPerm()) {
                let studentIds = JSON.parse(sessionStorage.getItem('studentIds'))
                let courseIds = this.selectList.map(o => o.id)
                let map = {studentIds:studentIds,courseIds:courseIds}
                addAssignedList({map:map,username:this.$Cookie.get("username")}).then(res => {
                    this.$message("分配成功")
                    sessionStorage.removeItem("studentIds")
                    this.$router.push('/educational/assigned')
                }).catch(err => {
                    console.log(err)
                })
            }
        }
    }
}
</script>
<style scoped>
.el-form-item {
    margin: 10px;
}
</style>
